﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.IO;

using CE.Mail;
using CE.Image;
using CE.Global;
using CE.User;
using CXDecryption;
using CE.Database;
using CE.CarInsurance;

public partial class car_insurance_payment_user_message : MyLanguageBasePage
{
    //protected override void InitializeCulture()
    //{
    //    String selectedCulture = CE.Global.General.SetCulture();
    //    //UICulture = selectedCulture;
    //    Culture = selectedCulture;
    //    base.InitializeCulture();
    //}

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HyperLink _lnkTryAgain = new HyperLink();
            ibtnTryAgain.Attributes.Add("onmouseover", "this.src='" + _lnkTryAgain.ResolveClientUrl(Resources.ImageResource.TryAgainGreenUrl) + "';");
            ibtnTryAgain.Attributes.Add("onmouseout", "this.src='" + _lnkTryAgain.ResolveClientUrl(Resources.ImageResource.TryAgainBlueUrl) + "';");
            if (Session[CE.Global.General.OrderRefNo] != null)
            {
                txtOrderRefNo.Text = Session[CE.Global.General.OrderRefNo].ToString();
                MyDatabase _db = new MyDatabase();
                Int64 CarId = 0;
                Int64 UserId = 0;
                Int16 PaymentCode = -1;
                bool PaymentStatus = false;
                Int16 NonPaymentStatus = -1;
                Int64 ProviderCompanyId = 0;
                string CITempResultId = "";
                string strSql = "";
                string QuoteRefNo = "";
                string AgentEmail = "";
                if (CheckApplicationType(txtOrderRefNo.Text.Trim()) == 1) //Online Application
                {
                    strSql = "SELECT ProviderCompanyId,CITempResultId,CarId FROM tblCarInsuranceSelectItemTH WHERE OrderRefNo  = '" + txtOrderRefNo.Text + "'";
                    DataTable _Providerresult = _db.GetDataTable(strSql);
                    if (_Providerresult != null && _Providerresult.Rows.Count > 0)
                    {
                        //ProviderCompanyId = Convert.ToInt64(_Providerresult.ToString());
                        ProviderCompanyId = Convert.ToInt64(_Providerresult.Rows[0]["ProviderCompanyId"].ToString());
                        CITempResultId = _Providerresult.Rows[0]["CITempResultId"].ToString();
                        CarId = Convert.ToInt64(_Providerresult.Rows[0]["CarId"].ToString());
                    }
                    strSql = "";
                    PaymentCode = -1;
                    PaymentStatus = false;
                    string TableName = GetCarMoreDetailsTableName(ProviderCompanyId);
                    strSql = "SELECT PaymentStatus,PaymentCode FROM " + TableName + " WHERE OrderRefNo  = '" + txtOrderRefNo.Text + "'";
                    DataTable _Paymentresult = _db.GetDataTable(strSql);
                    if (_Paymentresult != null && _Paymentresult.Rows.Count > 0)
                    {
                        PaymentStatus = Convert.ToBoolean(_Paymentresult.Rows[0]["PaymentStatus"].ToString());
                        PaymentCode = Convert.ToInt16(_Paymentresult.Rows[0]["PaymentCode"].ToString());
                        if (PaymentStatus == true)
                        //if (PaymentStatus == false)
                        {
                            divMsgType1.Visible = false;
                            divMsgType2.Visible = true;
                            divMsgType3.Visible = false;
                            if (Session[CE.Global.General.PayMailStatus] != null)
                            {
                                if (SendProposalToUserNEW(CITempResultId, CarId))
                                {
                                    Session[CE.Global.General.PayMailStatus] = null;
                                }
                            }
                            //Session[CE.Global.General.OrderRefNo] = null;
                        }
                        else
                        {
                            if (PaymentCode == 0)
                            {
                                divMsgType1.Visible = true;
                                divMsgType2.Visible = false;
                                divMsgType3.Visible = false;
                            }
                            else if (PaymentCode == 2)
                            {
                                divMsgType1.Visible = false;
                                divMsgType2.Visible = false;
                                divMsgType3.Visible = true;
                            }
                            else
                            {
                                divMsgType1.Visible = false;
                                divMsgType2.Visible = false;
                                divMsgType3.Visible = false;
                            }
                        }
                    }
                    else
                    {
                        divMsgType1.Visible = false;
                        divMsgType2.Visible = false;
                        divMsgType3.Visible = false;
                    }
                }
                else if (CheckApplicationType(txtOrderRefNo.Text.Trim()) == 2) //NonGG Application
                {                  
                    strSql = "";
                    PaymentCode = -1;
                    NonPaymentStatus = -1;
                    string TableName = GetCarMoreDetailsTableName(ProviderCompanyId);
                    strSql = "SELECT ONLPaymentStatus,ONLPaymentCode,RefCEUserId,QuoteRefNo,ProviderCompanyId,CECarId,AgentId FROM [tblNonGGCarMoreDetails] WHERE OrderRefNo  = '" + txtOrderRefNo.Text + "'";
                    DataTable _Paymentresult = _db.GetDataTable(strSql);
                    if (_Paymentresult != null && _Paymentresult.Rows.Count > 0)
                    {
                        NonPaymentStatus = Convert.ToInt16(_Paymentresult.Rows[0]["ONLPaymentStatus"].ToString());
                        PaymentCode = Convert.ToInt16(_Paymentresult.Rows[0]["ONLPaymentCode"].ToString());
                        UserId = Convert.ToInt64(_Paymentresult.Rows[0]["RefCEUserId"].ToString());
                        QuoteRefNo = _Paymentresult.Rows[0]["QuoteRefNo"].ToString();
                        CarId = Convert.ToInt64(_Paymentresult.Rows[0]["CECarId"].ToString());
                        ProviderCompanyId = Convert.ToInt64(_Paymentresult.Rows[0]["ProviderCompanyId"].ToString());
                        Int64 AgentId = Convert.ToInt64(_Paymentresult.Rows[0]["AgentId"].ToString());

                        //strSql = "Open Symmetric Key CXUserSym Decryption By Certificate CXUserCert SELECT Convert(varchar(50), DECRYPTBYKEY(EInfo1)) Email FROM [tblCEUser] WHERE UsrTypeId = 200 AND CEID  = " + AgentId.ToString() + " Close Symmetric Key CXUserSym";
                        strSql = "SELECT UC.Info1 SMPTKey FROM tblCEContact UC WHERE UC.RefCEUserId  = " + AgentId.ToString();
                        DataTable _dtAgentId = _db.GetDataTable(strSql);
                        if (_dtAgentId != null && _dtAgentId.Rows.Count > 0)
                        {
                            string SMTPKey = _dtAgentId.Rows[0]["SMPTKey"].ToString();
                            AgentEmail = GetSMTPAccount(SMTPKey.ToLower());
                            //AgentEmail = CE.Configuration.MyConfigurationManager.GetAppSettingValue(SMTPKey);
                            //AgentEmail = _dtAgentId.Rows[0]["Email"].ToString();
                        }
                        
                        
                        if (NonPaymentStatus == 1)
                        {
                            divMsgType1.Visible = false;
                            divMsgType2.Visible = true;
                            divMsgType3.Visible = false;
                            if (Session[CE.Global.General.PayMailStatus] != null)
                            {
                                if (SendNonGGProposalToUserNEW(QuoteRefNo, CarId, ProviderCompanyId, AgentEmail))
                                {
                                    Session[CE.Global.General.PayMailStatus] = null;
                                }
                            }
                        }
                        else
                        {
                            if (PaymentCode == 0)
                            {
                                divMsgType1.Visible = true;
                                divMsgType2.Visible = false;
                                divMsgType3.Visible = false;
                            }
                            else if (PaymentCode == 2)
                            {
                                divMsgType1.Visible = false;
                                divMsgType2.Visible = false;
                                divMsgType3.Visible = true;
                            }
                            else
                            {
                                divMsgType1.Visible = false;
                                divMsgType2.Visible = false;
                                divMsgType3.Visible = false;
                            }
                        }
                    }
                    else
                    {
                        divMsgType1.Visible = false;
                        divMsgType2.Visible = false;
                        divMsgType3.Visible = false;
                    }
                }
                else
                {
                    txtOrderRefNo.Text = "";
                    divMsgType1.Visible = false;
                    divMsgType2.Visible = false;
                    divMsgType3.Visible = false;
                }
            }
            else
            {
                txtOrderRefNo.Text = "";
                divMsgType1.Visible = false;
                divMsgType2.Visible = false;
                divMsgType3.Visible = false;
            }
        }
    }

    protected void ibtnTryAgain_Click(object sender, EventArgs e)
    {
        Session[CE.Global.General.OrderRefNo] = null;
        if (txtOrderRefNo.Text != "")
        {
            MyDatabase _db = new MyDatabase();
            float _fAmount = 0.0f;
            string strSql = "";
            if (CheckApplicationType(txtOrderRefNo.Text.Trim()) == 1) //Online Application
            {
                strSql = "SELECT CAST(AnnualPremium AS NUMERIC(10,2)) AS AnnualPremium FROM tblCarInsuranceSelectItemTH WHERE OrderRefNo  = '" + txtOrderRefNo.Text + "'";
            }
            if (CheckApplicationType(txtOrderRefNo.Text.Trim()) == 2) //NonGG Application
            {
                strSql = "SELECT CAST(TotalCollectedPremium AS NUMERIC(10,2)) AS AnnualPremium FROM tblNonGGCarMoreDetails WHERE OrderRefNo  = '" + txtOrderRefNo.Text + "'";
            }
            object _result = _db.ExecuteScalarSqlStatement(strSql);
            if (_result != null)
            {
                _fAmount = Convert.ToSingle(_result.ToString());
            }

            string _strAmount, eAmount, _strOrderRefNo, eOrderRefNo;
            _strAmount = ""; eAmount = ""; _strOrderRefNo = ""; eOrderRefNo = "";
            string key = "cxDAtravel";
            CXDecryption.Decryption cxd = new CXDecryption.Decryption();
            _strAmount = _fAmount.ToString();
            _strOrderRefNo = txtOrderRefNo.Text;
            if (_strAmount.ToString() != "" && _strAmount.ToString() != null)
            {
                byte[] Amount = cxd.Encrypt(_strAmount, key);
                eAmount = Convert.ToBase64String(Amount);
            }
            if (_strOrderRefNo.ToString() != "" && _strOrderRefNo.ToString() != null)
            {
                byte[] OrderRefNo = cxd.Encrypt(_strOrderRefNo, key);
                eOrderRefNo = Convert.ToBase64String(OrderRefNo);
            }
            string URL = ConfigurationManager.AppSettings["TH.BKKPaymentPage"].ToString();
            URL += "?pa=" + eAmount + "&orno=" + eOrderRefNo;
            Response.Redirect(URL);
        }
    }

    protected void ibtnTryAgainforCancel_Click(object sender, EventArgs e)
    {
        Session[CE.Global.General.OrderRefNo] = null;
        if (txtOrderRefNo.Text != "")
        {
            MyDatabase _db = new MyDatabase();
            float _fAmount = 0.0f;
            string strSql = "";
            if (CheckApplicationType(txtOrderRefNo.Text.Trim()) == 1) //Online Application
            {
                strSql = "SELECT CAST(AnnualPremium AS NUMERIC(10,2)) AS AnnualPremium FROM tblCarInsuranceSelectItemTH WHERE OrderRefNo  = '" + txtOrderRefNo.Text + "'";
            }
            if (CheckApplicationType(txtOrderRefNo.Text.Trim()) == 2) //NonGG Application
            {
                strSql = "SELECT CAST(TotalCollectedPremium AS NUMERIC(10,2)) AS AnnualPremium FROM tblNonGGCarMoreDetails WHERE OrderRefNo  = '" + txtOrderRefNo.Text + "'";
            }

            
            object _result = _db.ExecuteScalarSqlStatement(strSql);
            if (_result != null)
            {
                _fAmount = Convert.ToSingle(_result.ToString());
            }

            string _strAmount, eAmount, _strOrderRefNo, eOrderRefNo;
            _strAmount = ""; eAmount = ""; _strOrderRefNo = ""; eOrderRefNo = "";
            string key = "cxDAtravel";
            CXDecryption.Decryption cxd = new CXDecryption.Decryption();
            _strAmount = _fAmount.ToString();
            _strOrderRefNo = txtOrderRefNo.Text;
            if (_strAmount.ToString() != "" && _strAmount.ToString() != null)
            {
                byte[] Amount = cxd.Encrypt(_strAmount, key);
                eAmount = Convert.ToBase64String(Amount);
            }
            if (_strOrderRefNo.ToString() != "" && _strOrderRefNo.ToString() != null)
            {
                byte[] OrderRefNo = cxd.Encrypt(_strOrderRefNo, key);
                eOrderRefNo = Convert.ToBase64String(OrderRefNo);
            }
            string URL = ConfigurationManager.AppSettings["TH.BKKPaymentPage"].ToString();
            URL += "?pa=" + eAmount + "&orno=" + eOrderRefNo;
            Response.Redirect(URL);
        }
    }

    public string GetCarMoreDetailsTableName(Int64 ProviderId)
    {
        string _TableName = "";
        if (ProviderId == 11)
        {
            _TableName = "tblCarMoreDetail_AZCp";
        }
        else if (ProviderId == 12)
        {
            _TableName = "tblCarMoreDetail_MSIG";
        }
        else if (ProviderId == 16)
        {
            _TableName = "tblCarMoreDetail_AXA";
        }
        else if (ProviderId == 29)
        {
            _TableName = "tblCarMoreDetail_LMG";
        }
        else if (ProviderId == 31)
        {
            _TableName = "tblCarMoreDetail_Chartis";
        }
        else if (ProviderId == 32)
        {
            _TableName = "tblCarMoreDetail_BKI";
        }
        else if (ProviderId == 33)
        {
            _TableName = "tblCarMoreDetail_MTI";
        }
        else if (ProviderId == 35)
        {
            _TableName = "tblCarMoreDetail_KPI";
        }
        else if (ProviderId == 39)
        {
            _TableName = "tblCarMoreDetail_Mittare";
        }
        else if (ProviderId == 41)
        {
            _TableName = "tblCarMoreDetail_Kurnia";
        }
        else if (ProviderId == 43)
        {
            _TableName = "tblCarMoreDetail_SMK";
        }
        else if (ProviderId == 45)
        {
            _TableName = "tblCarMoreDetail_Viriyah";
        }
        else if (ProviderId == 46)
        {
            _TableName = "tblCarMoreDetail_TMS";
        }
        else if (ProviderId == 58)
        {
            _TableName = "tblCarMoreDetail_TVV";
        }
        return _TableName;
    }

    private bool SendProposalToUserNEW(string CITempResultId, Int64 CarId)
    {
        Int64 _carId = CarId;
        CE.User.Profile usrprofile = new Profile();
        ProfileDB usrprofiledb = new ProfileDB();

        usrprofile = usrprofiledb.GetProfile(Convert.ToInt64(Session[General.UserId].ToString()));

        string userfirstname = "";

        if (usrprofile != null)
        {
            userfirstname = usrprofile.FirstName;
        }

        string _refNo = "";
        CarDetailTH _cardetailth = new CarDetailTH();
        CarDetailTHDB _cardetailthdb = new CarDetailTHDB();
        CE.Database.MyDatabase _db = new CE.Database.MyDatabase();
        DataSet _dsInsurance = new DataSet();

        string _Premium = "";
        string _Gender = "";
        string _DOB = "";
        string _Occupation = "";
        string _InsuranceType = "";

        string _GarageType = "";
        string _CarYear = "";
        string _CarMakeModel = "";
        string _CarType = "";
        string _CarPlate = "";
        string _NameDriver = "";
        string _Name = "";
        string _PolicyStartDate = "";
        string _isCTPL = "No";
        string _CTPL = "";

        Int64 _companyId = 0;

        System.Data.DataTable _dtSeletectItem = new System.Data.DataTable("SelectedResultItem");
        _dtSeletectItem = _db.GetDataTable("Select * from tblCarInsuranceSelectItemTH WHERE CarId = " + _carId.ToString());
        if (_dtSeletectItem != null && _dtSeletectItem.Rows.Count > 0)
        {
            _companyId = Convert.ToInt64(_dtSeletectItem.Rows[0]["ProviderCompanyId"].ToString());
            _Premium = Convert.ToSingle(_dtSeletectItem.Rows[0]["AnnualPremium"].ToString()).ToString("#.00");
        }
        CarInsuranceCompletedItemDB _carinsurancecompleteditemdb = new CarInsuranceCompletedItemDB();
        _dsInsurance = _carinsurancecompleteditemdb.GetCarInsuranceCompletedItem(_carId, _companyId);
        if (_dsInsurance != null && _dsInsurance.Tables[0].Rows.Count > 0)
        {
            _Gender = _dsInsurance.Tables[0].Rows[0]["Gender"].ToString() == "Male" ? Resources.CarInsurance.Male : Resources.CarInsurance.Female;
            _DOB = Convert.ToDateTime(_dsInsurance.Tables[0].Rows[0]["DOB"]).ToString("dd-MMM-yyyy");
            if (CE.Global.General.SetCulture() == "th-TH")
            {
                _Occupation = _dsInsurance.Tables[0].Rows[0]["THOccupation"].ToString();
            }
            else
            {
                _Occupation = _dsInsurance.Tables[0].Rows[0]["ENOccupation"].ToString();
            }
            //lblInsuranceType.Text = _dsInsurance.Tables[0].Rows[0]["InsuranceType"].ToString();
            switch (_dsInsurance.Tables[0].Rows[0]["InsuranceType"].ToString())
            {
                case "Class 1":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOne;
                    break;
                case "Class 1 (Low Cost)":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOneLowCost;
                    break;
                case "Class 2+":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassTwoPlus;
                    break;
                case "Class 3+":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThreePlus;
                    break;
                case "Class 3":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThree;
                    break;
            }



            _GarageType = _dsInsurance.Tables[0].Rows[0]["GarageType"].ToString() == "Authorized" ? Resources.CarInsurance.Garage_Authorized : Resources.CarInsurance.Garage_Dealer;
            _CarYear = _dsInsurance.Tables[0].Rows[0]["CarModelYear"].ToString();
            _CarMakeModel = _dsInsurance.Tables[0].Rows[0]["MakeModelDesc"].ToString();
            _CarType = _dsInsurance.Tables[0].Rows[0]["VehicleType"].ToString() == "Private Use" ? Resources.CarInsurance.VehicleType_Private : Resources.CarInsurance.VehicleType_Commercial;
            //_CarPlate = _dsInsurance.Tables[0].Rows[0]["RedPlate"].ToString();
            //lblSumInsured.Text = Convert.ToSingle(_dsInsurance.Tables[0].Rows[0]["SumInsured"]).ToString("#,###") + " " + Resources.CarInsurance.Baht;
            //lblProvinceofRegistration.Text = _dsInsurance.Tables[0].Rows[0]["ProvinceRegistration"].ToString() == "Bangkok Metro Area" ? Resources.CarInsurance.Province_BKK : Resources.CarInsurance.Province_UPC;
            //lblAnyClaim.Text = _dsInsurance.Tables[0].Rows[0]["AnyClaim"].ToString() == "Yes" ? Resources.CarInsurance.Option_YesHave : Resources.CarInsurance.Option_NoHave;
            //lblNCB.Text = _dsInsurance.Tables[0].Rows[0]["NCB"].ToString() + "%";
            _NameDriver = _dsInsurance.Tables[0].Rows[0]["Driver"].ToString() == "Yes" ? Resources.CarInsurance.Option_YesSpecify : Resources.CarInsurance.Option_NoSpecify;

            if (_dsInsurance.Tables[1].Rows.Count > 0)
            {
                //    lblInsurer.Text = GetInsurer(_companyId);
                //    lblAnnualPremium.Text = Convert.ToSingle(_dsInsurance.Tables[1].Rows[0]["AnnualPremium"]).ToString("#,###.00") + " " + Resources.CarInsurance.Baht;
                //    lblCTPL.Text = _dsInsurance.Tables[1].Rows[0]["CTPL"].ToString() == "Yes" ? Resources.CarInsurance.Option_Yes : Resources.CarInsurance.Option_No;
                //    lblCTPLAmount.Text = Convert.ToSingle(_dsInsurance.Tables[1].Rows[0]["CTPLAmount"]).ToString("#.00") + " " + Resources.CarInsurance.Baht;
                //    lblPackage.Text = _dsInsurance.Tables[1].Rows[0]["CoverTypeDesc"].ToString();

                //    lblContactNo.Text = String.Format("{0:0##-###-####}", Convert.ToInt32(_dsInsurance.Tables[1].Rows[0]["ContactNo"]));
                //    lblVehicleNo.Text = _dsInsurance.Tables[1].Rows[0]["VehicleNo"].ToString();
                //    lblEngineNo.Text = _dsInsurance.Tables[1].Rows[0]["EngineNo"].ToString();
                //    lblChassisNo.Text = _dsInsurance.Tables[1].Rows[0]["ChassisNo"].ToString();
                //    lblVehicleColor.Text = _dsInsurance.Tables[1].Rows[0]["VehicleColor"].ToString();
                //    lblVehicleProvince.Text = _dsInsurance.Tables[1].Rows[0]["VehicleProvince"].ToString();

                _CarPlate = _dsInsurance.Tables[1].Rows[0]["VehicleNo"].ToString();
                if (_dsInsurance.Tables[1].Rows[0]["PolicyStartDate"] != DBNull.Value)
                {
                    _PolicyStartDate = Convert.ToDateTime(_dsInsurance.Tables[1].Rows[0]["PolicyStartDate"]).ToString("dd-MMM-yyyy");
                }
                _Name = _dsInsurance.Tables[1].Rows[0]["Name"].ToString();
                _refNo = _dsInsurance.Tables[1].Rows[0]["QuoteRefNo"].ToString();

                _isCTPL = _dsInsurance.Tables[1].Rows[0]["CTPL"].ToString();
                _CTPL = _dsInsurance.Tables[1].Rows[0]["CTPLAmount"].ToString();
            }
            //lblQuoteTitle.Text = Resources.CarInsurance.QuoteRefNo + " : " + _refNo + " - " + Resources.CarInsurance.CarInsuranceList + " " + lblCarMakeModel.Text;
        }

        bool _retVal = false;
        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive");

        string _emailTo = Session[General.UserEmail].ToString();
        //string _emailTo = "sophon.vorasitchai@comparexpress.com";
        string _customername = Session[General.UserName].ToString();
        string _emailSubject = "<Online> " + Resources.EmailMessage.Subject; // "Your Car Insurance Quotes on CompareXpress(Thailand)";
        string _mailBody = "";
        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        //string _currentDomainUrl = "http://www.GluayGluay.com";
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");

        #region old english body

        //_mailBody = "<body class='email_body'>";
        //_mailBody += "<style type='text/css'>";
        //_mailBody += ".email_body {background: white;margin: 0;padding: 0;color: #4c4c4c;font-family: Arial, Helvetica, sans-serif;font-size: 0.85em;}";
        //_mailBody += "a {text-decoration:underline;color:#2c95cc;} ";
        //_mailBody += "#email_container {margin:0 auto;padding:20px;width:600px; height:auto;} ";
        //_mailBody += "#email_body {width:100%; text-align: left !important;} ";
        //_mailBody += ".email_pad10px {padding:10px;} ";
        //_mailBody += ".email_results td {width:33%;} ";
        //_mailBody += "</style>";
        //_mailBody += "<center> <br /><br />";

        //_mailBody += "<table cellpadding='0' cellspacing='0' border='0' width='570'>";
        //_mailBody += "<tr><td width='570'><table cellspacing='0' cellpadding='0' width='100%' border='0'>";
        //_mailBody += "<tr><td width='50%' valign='top'><strong>Order Confirmation</strong><br /><br />Thank you for choosing GluayGluay.com <br/><br/>";
        //_mailBody += "<br/><strong>Order No. (Reference No.): </strong>" + _refNo + "</td><td width='50%' align='right' valign='top'><img src='" + _currentDomainUrl + "/images/public/logo/logo_gluaygluay.png' width='130' height='99'/></td></tr>";
        //_mailBody += "</table>";

        //_mailBody += "<table cellspacing='0' cellpadding='2' width='570' border='0'>";
        //_mailBody += " <tr><td width='50%' valign='top'>Insurance Type: " + _InsuranceType + "</td><td width='50%;' valign='top'>&nbsp;</td>";
        //_mailBody += "</tr><tr><td valign='top'>Ref. No. " + _refNo + "</td><td valign='top'>Order Date: " + General.GetUTCDateTime().ToString("dd/MMM/yyyy") + "</td></tr>";
        //_mailBody += "<tr><td valign='top'>Name-Lastname: " + _Name + "</td><td valign='top'>License Plate No.: " + _CarPlate + "</td></tr>";
        //_mailBody += "<tr><td valign='top'>Make/Model: " + _CarMakeModel + "</td><td valign='top'>Car Year: " + _CarYear +"</td></tr>";
        //_mailBody += "<tr><td valign='top'>Garage Type: " + _GarageType + "</td><td valign='top'>Name Drivers: " + _NameDriver + "</td></tr>";
        //_mailBody += "<tr><td valign='top'>Policy Start Date: " + _PolicyStartDate + " </td><td valign='top'></td></tr>";
        //_mailBody += "</table> <br /><br />";

        #endregion

        _mailBody = "<body class='email_body'>";
        _mailBody += "<style type='text/css'>";
        _mailBody += ".email_body {background: white;margin: 0;padding: 0;color: #4c4c4c;font-family: Arial, Helvetica, sans-serif;font-size: 0.85em;}";
        _mailBody += "a {text-decoration:underline;color:#2c95cc;} ";
        _mailBody += "#email_container {margin:0 auto;padding:20px;width:600px; height:auto;} ";
        _mailBody += "#email_body {width:100%; text-align: left !important;} ";
        _mailBody += ".email_pad10px {padding:10px;} ";
        _mailBody += ".email_results td {width:33%;} ";
        _mailBody += "</style>";
        _mailBody += "<center> <br /><br />";

        _mailBody += "<table cellpadding='0' cellspacing='0' border='0' width='570'>";
        _mailBody += "<tr><td width='570'><table cellspacing='0' cellpadding='0' width='100%' border='0'>";
        _mailBody += "<tr><td width='50%' valign='top'><strong>" + Resources.Proposal.OrderConfirmation + "</strong><br /><br />";
        _mailBody += Resources.Proposal.ThankYou + "<br/><br/>";
        _mailBody += "<br/><strong>" + Resources.Proposal.OrderNo + " </strong>" + _refNo + "</td><td width='50%' align='right' valign='top'><img src='" + _currentDomainUrl + "/images/public/logo/logo_gluaygluay.png' width='130' height='99'/></td></tr>";
        _mailBody += "</table>";

        _mailBody += "<table cellspacing='0' cellpadding='2' width='570' border='0'>";
        _mailBody += " <tr><td width='50%' valign='top'>" + Resources.Proposal.InsuranceType + " " + _InsuranceType + "</td><td width='50%;' valign='top'>&nbsp;</td>";
        _mailBody += "</tr><tr><td valign='top'>" + Resources.Proposal.RefNo + ": " + _refNo + "</td><td valign='top'>" + Resources.Proposal.OrderDate + ": " + General.GetUTCDateTime().ToString("dd/MMM/yyyy") + "</td></tr>";
        _mailBody += "<tr><td valign='top'>" + Resources.Proposal.NameLastname + ": " + _Name + "</td><td valign='top'>" + Resources.Proposal.LicensePlateNo + ": " + _CarPlate + "</td></tr>";
        _mailBody += "<tr><td valign='top'>" + Resources.Proposal.MakeModel + ": " + _CarMakeModel + "</td><td valign='top'>" + Resources.Proposal.CarYear + ": " + _CarYear + "</td></tr>";
        _mailBody += "<tr><td valign='top'>" + Resources.Proposal.GarageType + ": " + _GarageType + "</td><td valign='top'>" + Resources.Proposal.NamedDrivers + ": " + _NameDriver + "</td></tr>";
        _mailBody += "<tr><td valign='top'>" + Resources.Proposal.PolicyStartDate + ": " + _PolicyStartDate + " </td><td valign='top'></td></tr>";
        _mailBody += "</table> <br /><br />";

        DataSet _dsResults = new DataSet();
        DataView dvResults = new DataView();
        SortedList _sPara = new SortedList();
       
        _sPara.Add("@CarId", _carId);
        _sPara.Add("@RefUserId", Convert.ToInt64(Session[General.UserId].ToString()));
        _dsResults = _db.GetDataSet("sprocCarInsuranceResultSelectItemList", _sPara);
        if (_dsResults.Tables.Count > 0 && _dsResults.Tables[0].Rows.Count > 0)
        {
            dvResults = _dsResults.Tables[0].DefaultView;// ((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + _carId]);
            dvResults.RowFilter = " CITempResultId in (" + CITempResultId + ")";
        }
        _mailBody += "<table cellpadding='5' cellspacing='0' border='0' width='100%' class='table_details'>";

        //string CITempResultId = inputCarResultId.Value;

        DataTable dtResults = dvResults.ToTable();


        if (dtResults.Rows.Count > 0)
        {
            string _providercompanyid = dtResults.Rows[0]["providercompanyid"].ToString();
            //logo
            string logourl = CE.Global.General.GetProviderCompanyLogo(_providercompanyid);

            _mailBody += "<tr>";
            _mailBody += "<td width='45%'></td>";
            _mailBody += "<td width='55%' align='center' style='background:#e0e0e0; border-bottom:white 1px dashed;'><img src='" + _currentDomainUrl + logourl + "' width='130' style='padding:3px;'/></td>";
            _mailBody += "</tr>";

            string insurername = dtResults.Rows[0]["PackageName"].ToString();

            //insurer name
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.Insurer + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5; color:white;'><strong>" + insurername + "</strong></td>";
            _mailBody += "</tr>";

            float _fMonthlyPremiumAmount = Convert.ToSingle(dtResults.Rows[0]["MonthlyPremiumAmount"].ToString());
            string monthlyInstallment = "";

            if (_fMonthlyPremiumAmount > 0.0f)
            {
                string _monthlyPremiumAmount = String.Format("{0:0,0.00}", _fMonthlyPremiumAmount);
                monthlyInstallment = _monthlyPremiumAmount + "/mth<br/>";
            }
            else
            {
                monthlyInstallment = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }

            //installment
            //_mailBody += "<tr>";
            //_mailBody += "<td><strong>"+ Resources.CarInsuranceResultPage.MonthlyInstallment  +" <br/>4-mth 0% Interest Free</strong></td>";
            //_mailBody += "<td align='center' style='background:#d5d5d5' >" + monthlyInstallment + "</td>";
            //_mailBody += "</tr>";

            //Deductible  
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.DEC + "</strong></td>";
            float _fDEC = Convert.ToSingle(dtResults.Rows[0]["DEC"].ToString());
            string deductible = "";
            if (_fDEC > 0.0f)
            {
                deductible = String.Format("{0:0,0.00}", _fDEC);
            }
            else
            {
                deductible = Resources.CarInsuranceResultPage.Waived;  //"<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + deductible + "</td>";
            _mailBody += "</tr>";

            string suminsured = String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["SumInsured"].ToString()));
            if (suminsured == "0")
            {
                suminsured = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            //Own Damage
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.OwnDamage + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + suminsured + "</td>";
            _mailBody += "</tr>";

            //Fire
            string fire = String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["Fire"].ToString()));
            if (fire == "0")
            {
                fire = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.Fire + "</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + fire + "</td>";
            _mailBody += "</tr>";

            //Theft
            string theft = String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["Theft"].ToString()));
            if (theft == "0")
            {
                theft = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.Theft + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + theft + "</td>";
            _mailBody += "</tr>";

            //TPPD
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.TPPD + "</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["TPPD"].ToString())) + "</td>";
            _mailBody += "</tr>";

            //TPBIA
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.TPBIA + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["TPBIA"].ToString())) + "</td>";
            _mailBody += "</tr>";

            //TPBIP
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.TPBIP + "</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["TPBIP"].ToString())) + "</td>";
            _mailBody += "</tr>";

            //PA Driver
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.PADriver + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["PADriver"].ToString())) + "</td>";
            _mailBody += "</tr>";


            int _MedicalExpense = Convert.ToInt32(dtResults.Rows[0]["MedicalExpense"].ToString());
            string medicalExpense = "";

            if (_MedicalExpense == 0)
            {
                medicalExpense = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            else
            {
                medicalExpense = String.Format("{0:#,0}", Convert.ToSingle(_MedicalExpense.ToString()));
            }

            //Medical Expense
            _mailBody += "<tr>";
            _mailBody += "<td><strong>" + Resources.CarInsuranceResultPage.MED + "</strong></td>";
            _mailBody += "<td align='center' style='background:#c5c5c5' >" + medicalExpense + "</td>";
            _mailBody += "</tr>";

            //BB
            _mailBody += "<tr>";
            _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.BailBond + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5' >" + String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["BailBond"].ToString())) + "</td>";
            _mailBody += "</tr>";

            //CTPL
            if (_isCTPL == "Yes")
            {
                //premium before ctpl
                _mailBody += "<tr>";
                _mailBody += "<td align='left' ><strong>" + Resources.CarInsuranceResultPage.AnnualPremium + "</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";

                double BeforeCTPL = Convert.ToSingle(_Premium) - Convert.ToSingle(_CTPL);

                if (Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString()) != Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"]))
                {
                    _mailBody += "<s>" + String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString())) + "</s>";
                }

                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(BeforeCTPL)) + "</strong>";
                _mailBody += "</td>";
                _mailBody += "</tr>";

                //ctplamount
                _mailBody += "<tr>";
                _mailBody += "<td align='left' ><strong>" + Resources.CarInsuranceResultPage.CTPL + "</strong></td>";
                _mailBody += "<td align='center' style='background:#d5d5d5;'>";

                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_CTPL)) + "</strong>";
                _mailBody += "</td>";
                _mailBody += "</tr>";

            }


            //premium
            _mailBody += "<tr>";
            _mailBody += "<td align='left' ><strong>" + Resources.CarInsuranceResultPage.TotalVMI + "</strong></td>";
            _mailBody += "<td align='center' style='background:#d5d5d5; color:F00; font-size:20px;'>";

            if (_isCTPL == "No")
            {
                if (Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString()) != Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"]))
                {
                    _mailBody += "<s>" + String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString())) + "</s>";
                }

                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"].ToString())) + "</strong>";
            }
            else
            {
                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_Premium)) + "</strong>";
            }


            _mailBody += "</td>";
            _mailBody += "</tr>";


            #region remove

            //bool _IsPersonnalEffectsLoss = false;// Convert.ToBoolean(dtResults.Rows[0]["IsPersonnalEffectsLoss"].ToString());
            //int _LossPE = Convert.ToInt32(dtResults.Rows[0]["BailBond"].ToString());
            //string lossPE = "";

            //if (!_IsPersonnalEffectsLoss)
            //{
            //    lossPE = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            //}
            //else
            //{
            //    lossPE = String.Format("${0:#,0}", Convert.ToSingle(_LossPE.ToString()));
            //}

            ////Loss of Personal Effects
            //_mailBody += "<tr>";
            //_mailBody += "<td><strong>Loss of Personal Effects</strong></td>";
            //_mailBody += "<td align='center' style='background:#d5d5d5' >" + lossPE + "</td>";
            //_mailBody += "</tr>";

            //string _CarReplace = "test";// dtResults.Rows[0]["CarReplacement"].ToString();
            //bool _IsCarReplace = false; // Convert.ToBoolean(dtResults.Rows[0]["IsCarReplacement"].ToString());
            //bool _IsTranspoAllowance = false;// Convert.ToBoolean(dtResults.Rows[0]["isCashAllowance"].ToString());
            //string _strTranspoAllowance = "99";// Convert.ToString(dtResults.Rows[0]["CashAllowance"].ToString());
            //string _strMaxTranspoAllowanceDays = "100";// Convert.ToString(dtResults.Rows[0]["MaxCashAllowanceDays"].ToString());
            //string lossUse = "";

            //if (_IsCarReplace)
            //{
            //    lossUse = "Courtesy Car <br/>" + "max " + _CarReplace.ToString() + " day(s)";
            //}
            //else
            //{
            //    if (_IsTranspoAllowance)
            //    {
            //        lossUse = "Transport Allowance<br/> S$" + _strTranspoAllowance + "/day <br/> max " + _strMaxTranspoAllowanceDays + " day(s)";
            //    }
            //    else
            //    {
            //        lossUse = "<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            //    }

            //}

            ////Loss of Use (Benefit) 
            //_mailBody += "<tr>";
            //_mailBody += "<td><strong>Loss of Use</strong> (Benefit)</td>";
            //_mailBody += "<td align='center' style='background:#c5c5c5' >" + lossUse + "</td>";
            //_mailBody += "</tr>";


            //string viewworkshops = "";

            //if (_providercompanyid == "29")
            //{
            //    viewworkshops = "<a href='http://www.libertyinsurance.com.sg/pdf/PWS%20Nov05.pdf' target='_blank'><img src='" + _currentDomainUrl + "/images/icon/pdf.png' alt='workshops' width='23' alt='NA' border='0' /></a>";
            //}
            //else if (_providercompanyid == "30")
            //{
            //    viewworkshops = "<a href='" + _currentDomainUrl + "/policy_docs/Etiqa/Etiqa - AWS Listing.pdf' target='_blank'><img src='" + _currentDomainUrl + "/images/icon/pdf.png' alt='workshops' width='23' alt='NA' border='0' /></a>";
            //}
            //else
            //{
            //    viewworkshops = "<a href='" + _currentDomainUrl + "/policy_docs/HSBC/HSBCworkshops.pdf' target='_blank'><img src='" + _currentDomainUrl + "/images/icon/pdf.png' alt='workshops' width='23' alt='NA' border='0' /></a>";
            //}

            ////View Workshops
            //_mailBody += "<tr>";
            //_mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>View Workshops</strong></td>";
            //_mailBody += "<td align='center' style='background:#d5d5d5' >" + viewworkshops + "</td>";
            //_mailBody += "</tr>";


            //string _policyId = "0";// dtResults.Rows[0]["NInfo1"].ToString();

            //ProviderPolicyDocument _policydoc = new ProviderPolicyDocument();
            //ProviderPolicyDocumentDB _policydocdb = new ProviderPolicyDocumentDB();

            //_policydoc = _policydocdb.GetProviderPolicyDocument(Convert.ToInt64(_policyId));

            //string docurl = "";// _currentDomainUrl + _policydoc.UploadPath.Remove(0, 1);
            //string viewpolicywordings = "<a href='" + docurl + "' ><img src='" + _currentDomainUrl + "/images/icon/pdf.png'  alt='policy wordings' width='23' alt='NA' border='0'/></a>";

            ////View Policy Wordings
            //_mailBody += "<tr>";
            //_mailBody += "<td><strong>View Policy Wordings</strong></td>";
            //_mailBody += "<td align='center' style='background:#c5c5c5' >" + viewpolicywordings + "</td>";
            //_mailBody += "</tr>";

            //if (_providercompanyid == "23")
            //{
            //    string endorsementlink = "";

            //    int _coverid = Convert.ToInt32(dtResults.Rows[0]["CoverTypeId"].ToString());

            //    if (_coverid == 2 || _coverid == 6) //classic
            //    {
            //        endorsementlink = _currentDomainUrl + "/policy_docs/HSBC/PCIClassicPlan.pdf";
            //    }
            //    else
            //    {
            //        endorsementlink = _currentDomainUrl + "/policy_docs/HSBC/PCIPremierPlan.pdf";
            //    }


            //    string viewendorsements = "<a href='" + endorsementlink + "' target='_blank' id='lnkendorse'><img src='" + _currentDomainUrl + "/images/icon/pdf.png' width='23' alt='NA' border='0' /></a>";

            //    //View Policy Endorsements
            //    _mailBody += "<tr>";
            //    _mailBody += "<td style='border-bottom:1px solid #ccc;'><strong>View Endorsements</strong></td>";
            //    _mailBody += "<td align='center' style='background:#d5d5d5' >" + viewendorsements + "</td>";
            //    _mailBody += "</tr>";
            //}

            #endregion

        }

        _mailBody += "</table>";
        _mailBody += "<br/><br/>";
        _mailBody += "<u>" + Resources.Proposal.ForBankIn + "</u>";
        _mailBody += "<br/>" + Resources.Proposal.ForBankInMsg1;


        _mailBody += "<br/>";

        _mailBody += "<br/>" + Resources.Proposal.ForBankInMsg2;

        _mailBody += "<br/>";

        _mailBody += "<br/><strong>" + Resources.Proposal.Remarks + "</strong>";
        _mailBody += "<br/>" + Resources.Proposal.RemarksMsg1;
        _mailBody += "<br/>";
        _mailBody += "<br/><strong>" + Resources.Proposal.CompareXpress + "</strong>";
        _mailBody += "<br/>" + Resources.Proposal.CompareXpressAddress;

        #region englishBody

        //_mailBody += "</table>";
        //_mailBody += "<br/><br/>";
        //_mailBody += "<u>For Bank-in Customers</u>";
        //_mailBody += "<br/>Please transfer the money to GluayGluay.com within 7 days after placing the order";
        //_mailBody += "<br/>Saving Account No. 101-8-57590-0  Bangkok Bank, Head Office Branch";
        //_mailBody += "<br/>Account Name: Comparexpress Non-life Insurance Broker (Thailand) Ltd.";
        //_mailBody += "<br/>Please contact 02-268-8222 to notify your payment or fax /e-mail the proof of payment to 02-266-6321";
        //_mailBody += "<br/>or support@gluaygluay.com";

        //_mailBody += "<br/>";

        //_mailBody += "<br/>Please also prepare additional documents and fax/e-mail it to 02-266-6321 or support@gluaygluay.com";
        //_mailBody += "<br/>1. Copy of vehicle registration";
        //_mailBody += "<br/>2. Policy schedule of previous year or nenewal notification";
        //_mailBody += "<br/>3. Copy of driver's license (for named drivers)";

        //_mailBody += "<br/>";

        //_mailBody += "<br/><strong>Remarks:</strong>";
        //_mailBody += "<br/>1. The quotation valid for 30 days and subject to change without notice according to policy of company";
        //_mailBody += "<br/>2. Premium and coverage are subject to underwriting criteria of insurance company.";
        //_mailBody += "<br/>   We will keep you informed, should there be any further changes by the insurer";
        //_mailBody += "<br/>3. The coverage will commence after premium has been paid and ";
        //_mailBody += "<br/>   additional documents are completed and summited to us";
        //_mailBody += "<br/>4. In case of changes in premium made by insurer, we will contact you immediately for";
        //_mailBody += "<br/>   refunding (overpaid cases) or notifying you to pay more premium (underpaid cases)";

        //_mailBody += "<br/>";
        //_mailBody += "<br/><strong>Comparexpress Non-life Insurance Broker (Thailand) Ltd.</strong>";
        //_mailBody += "<br/>Non-life Insurance Broker License Number: ว00016/2553";
        //_mailBody += "<br/>2 K.C.C. Bldg. 2nd Floor, Silom Soi 9, Silom Road Bangrak Bangkok 10500";
        //_mailBody += "<br/>Tel. 02-268-8222  Fax. 02-266-6321";
        //_mailBody += "<br/>email: support@gluaygluay.com ";

        #endregion

        //_mailBody += "<br/><br/>" + Resources.EmailMessage.Details + "<br/><br/>";
        //_mailBody += " <a href='http://www.gluaygluay.com/car-insurance/sign-in.aspx'>CompareXpress.co.th</a> <br/><br/>";

        //_mailBody += "Enter your Email and Password as follows: <br/>";

        //Account _account = new Account();
        //AccountDB _accountdb = new AccountDB();
        //_account = _accountdb.GetAccount(Convert.ToInt64(Session[General.UserId].ToString()));
        //if (_account != null)
        //{
        //    _mailBody += "<br /> User Name : " + Session[General.UserEmail].ToString();
        //    _mailBody += "<br /> Password : " + _account.AuthCode + "<br/><br/>";

        //}


        _mailBody += "</td></tr>";
        //_mailBody += "<tr><td id='email_footer'><a href='http://www.gluaygluay.com' target='_blank'><img src='" + _currentDomainUrl + "/images/email/footer_quote.png' alt='CompareXpress - Partners' width='596' border='0' /></a>";
        _mailBody += "<tr><td id='email_footer'>";
        _mailBody += "</td></tr></table>";

        _mailBody += "<hr />";
        _mailBody += Resources.EmailMessage.Footer;
        _mailBody += "<br/>";
        _mailBody += "<br /><i>" + Resources.EmailMessage.NoReply + "</i>";
        _mailBody += "<hr />";
        _mailBody += "</center></body>";

        if (MyMailManager.SendSelectedCARMessage(_emailTo, _emailSubject + " (Ref No : " + _refNo + ") ", _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }

    private bool SendNonGGProposalToUserNEW(string QuoteRefNo, Int64 CarId, Int64 ProviderId, string AgentEmail)
    {
        bool _retVal = false;
        try
        {
            PaymentReceiptPDFOutput _payment = CreatePaymentPDFObject(CarId, ProviderId);
            string _fileName = _payment.GeneratePDF();
            if (_fileName != string.Empty)
            {
                FileInfo file = new System.IO.FileInfo(_fileName);

                if (file.Exists)
                {
                    string[] _file = new string[1];
                    _file[0] = _fileName;

                    string _toemail = Session[General.UserEmail].ToString();
                    string _ccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CI_BCC"); 
                     _ccemail += AgentEmail;
                    string _bccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SUPPORT");
                    string _customerName = Session[General.UserName].ToString();
                    string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LogoPath");
                    string _emailTitle = string.Empty;
                    _emailTitle = "<Online> เอกสารยืนยันการชำระค่าเบี้ยประกันภัย " + QuoteRefNo.ToString();
                    string mailBody = @"เรียน คุณ <strong>" + _customerName + "</strong><br/><br/>" +
                    "ขอบคุณที่ใช้บริการของเว็บไซต์ <a href='http://www.gluaygluay.com'>GluayGluay.com</a><br/>" +
                    "บริษัทฯขอนำส่งเอกสารยืนยันการชำระค่าเบี้ยประกันภัยให้ท่าน เพื่อเป็นหลักฐานในการสั่งซื้อ (โปรดดูไฟล์แนบ) <br/>" +
                    "ทั้งนี้ เอกสารใบเสร็จรับเงินตัวจริงจะถูกออกโดยบริษัทประกันฯ และจะส่งให้ท่านพร้อมกับเอกสารกรมธรรม์ต่อไป ขอบคุณค่ะ<br/>" +

                    "<br/>ขอแสดงความนับถือ<br/>" +
                    "<img src='" + imgUrl + "' alt='GluayGluay' width='120' height='100' /><br/>" +
                    "<br/><strong><a href='http://www.gluaygluay.com'>GluayGluay.com</a> Support Team</strong><br/>" +

                    "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                    "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                    "2 อาคาร เค.ซี.ซี. ชั้น 2 สีสมซอย 9 ถนนสีลม เขตบางรัก 10500<br/>" +
                    "โทร. 02-268-8222 โทรสาร 02-266-6339<br/>" +
                    "อีเมล์: support@gluaygluay.com<br/>" +
                    "กด Like เพื่อติดตามเราได้ใน Facebook: www.facebook.com/GGmotor";

                    if (MyMailManager.SendMailWithAttach(_customerName,_toemail, _ccemail,_bccemail, _emailTitle, mailBody, _file))
                    {
                        _retVal = true;
                    }
                    else
                    {
                        _retVal = false;
                    }
                }
                else
                {
                    _retVal = false;
                    //lblSendPaymentReceiptMessage.Text = "PDF generating failed.";
                }
            }
            else
            {
                _retVal = false;
                //lblSendPaymentReceiptMessage.Text = "PDF generating failed. No item found.";
            }

        }
        catch (Exception Ex)
        {
            _retVal = false;            
        }

        return _retVal;
    }

    private Int16 CheckApplicationType(string OrderRefNo)
    {
        Int16 _result = 0;
        if (OrderRefNo.Length > 11)
        {
            string val = "0";
            val = OrderRefNo.Substring(10, 1);
            _result = Convert.ToInt16(val);
        }
        return _result;
    }

    private PaymentReceiptPDFOutput CreatePaymentPDFObject(Int64 CECarId, Int64 CXBrokerProviderId)
    {
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXCRMBrokerPremiumSelectSingleItem";
        _sPara.Add("@CXBrokerProviderId", CXBrokerProviderId);
        _sPara.Add("@CECarId", CECarId);
        _sPara.Add("@SelectedStatus", true);
        DataSet _dsPayment = new DataSet();
        _dsPayment = _db.GetDataSet(_spName, _sPara);

        string _strFinalAnnualPremium = "0";
        string _strPaymentCash = "0";
        string _strPaymentCreditCard = "0";
        string _strPaymentBankTransfer = "0";
        string _strPaymentVisa = "0";
        string _strPaymentMaster = "0";
        string _strPaymentCheckNo = "0";
        string _strQuoteRefNo = "";
        string _strCustomerName = "";
        string _strCustomerAddress1 = "";
        string _strCustomerAddress2 = "";
        string _strCustomerAddress3 = "";
        string _strTypeOfPolicy = "";
        string _strCarMakeModel = "";
        DataSet _dsNonGG = new DataSet();
        _dsNonGG = GetNonGGApplication(CECarId, CXBrokerProviderId,0);
        if (_dsNonGG != null && _dsNonGG.Tables.Count > 0 && _dsNonGG.Tables[0].Rows.Count > 0)
        {
            _strCustomerAddress1 = _dsNonGG.Tables[0].Rows[0]["PresentAddress"].ToString();
            _strCustomerAddress2 = _dsNonGG.Tables[0].Rows[0]["SubDistrict"].ToString();
            _strCustomerAddress2 += ", " + _dsNonGG.Tables[0].Rows[0]["District"].ToString();

            _strCustomerAddress3 = _dsNonGG.Tables[0].Rows[0]["Province"].ToString();
            _strCustomerAddress3 += ", Thailand";
            _strCustomerAddress3 += " " + _dsNonGG.Tables[0].Rows[0]["Postalcode"].ToString();

            _strCarMakeModel = _dsNonGG.Tables[0].Rows[0]["CarMakeModel"].ToString();
            _strTypeOfPolicy = _dsNonGG.Tables[0].Rows[0]["InsuranceType"].ToString();

            _strCustomerName = _dsNonGG.Tables[0].Rows[0]["Name"].ToString();
            _strQuoteRefNo = _dsNonGG.Tables[0].Rows[0]["QuoteRefNo"].ToString();
            _strFinalAnnualPremium = _dsNonGG.Tables[0].Rows[0]["TotalCollectedPremium"].ToString();
        }

        //if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
        //{
        //    for (int i = 0; i < _dsPayment.Tables[1].Rows.Count; i++)
        //    {
        //        string _paymentType = _dsPayment.Tables[1].Rows[i]["PaymentTypeID"].ToString().ToLower();
        //        string _cardType = _dsPayment.Tables[1].Rows[i]["CardType"].ToString().ToLower();
        //        if (_paymentType == "cash")
        //        {
        //            _strPaymentCash = "1";
        //        }
        //        else if (_paymentType == "bktr")
        //        {
        //            _strPaymentBankTransfer = "1";
        //        }
        //        else if (_paymentType == "ccip" || _paymentType == "ccol")
        //        {
        //            _strPaymentCreditCard = "1";
        //            if (_cardType == "visa")
        //            {
        //                _strPaymentVisa = "1";
        //            }
        //            else if (_cardType == "mastercard")
        //            {
        //                _strPaymentMaster = "1";
        //            }
        //        }
        //    }

            
        //}
        _strPaymentCreditCard = "1";
        PaymentReceiptPDFOutput _paymentPDF = new PaymentReceiptPDFOutput();
        _paymentPDF.QuoteRefNo = _strQuoteRefNo.ToString();
        _paymentPDF.CustomerName = _strCustomerName.ToString();
        _paymentPDF.Address1 = _strCustomerAddress1.ToString();
        _paymentPDF.Address2 = _strCustomerAddress2.ToString();
        _paymentPDF.Address3 = _strCustomerAddress3.ToString();
        _paymentPDF.AnnualPremium = _strFinalAnnualPremium.ToString();
        _paymentPDF.TypeOfPolicy = _strTypeOfPolicy.ToString();
        _paymentPDF.MakeModel = _strCarMakeModel.ToString();

        if (_strPaymentBankTransfer.ToString() == "1")
        {
            _paymentPDF.IsBankTransfer = true;
        }

        if (_strPaymentCash.ToString() == "1")
        {
            _paymentPDF.IsCash = true;
        }

        if (_strPaymentCreditCard.ToString() == "1")
        {
            _paymentPDF.IsCreditCard = true;
        }

        if (_strPaymentMaster.ToString() == "1")
        {
            _paymentPDF.IsMaster = true;
        }

        if (_strPaymentVisa.ToString() == "1")
        {
            _paymentPDF.IsVisa = true;
        }

        if (_strPaymentCheckNo.ToString() != string.Empty)
        {
            if (_strPaymentCheckNo.ToString() != "0")
            {
                _paymentPDF.IsCheckNo = true;
                _paymentPDF.CheckNo = _strPaymentCheckNo.ToString();
            }
        }
        return _paymentPDF;
    }

    public DataSet GetNonGGApplication(Int64 CECarId, Int64 ProviderId, Int16 IsInternal)
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocCXCRMNonGGApplicationSelectItem]";

        SortedList _spara = new SortedList();
        _spara.Add("@CECarId", CECarId);
        _spara.Add("@ProviderCompanyId", ProviderId);
        _spara.Add("@IsInternal", IsInternal);

        DataSet _ds = _db.GetDataSet(_spName, _spara);

        return _ds;
    }

    private string GetSMTPAccount(string smtpKey)
    {
        string _retValue = string.Empty;
        if (smtpKey == "admin")
        {
            _retValue = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ADMINSMTPAccount");
        }
        else if (smtpKey == "cashier")
        {
            _retValue = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.CASHSMTPAccount");
        }
        else if (smtpKey == "broker1")
        {
            _retValue = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.Broker1SMTPAccount");
        }
        else if (smtpKey == "broker2")
        {
            _retValue = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.Broker2SMTPAccount");
        }
        else if (smtpKey == "broker3")
        {
            _retValue = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.Broker3SMTPAccount");
        }
        return _retValue;
    }

}
